package com.simple.util.file.image;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Element;
import sun.misc.BASE64Encoder;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * @program: simple_tools
 * @description:
 * @author: Mr.chen
 * @create: 2020-06-08 16:34
 **/
public class ImageUtil {
    // 比例
    public static final String PROPORTION = "{\"original\":{\"width\":%s,\"height\":%s},\"thumb\":{\"width\":%s,\"height\":%s}}";

    public final static Color[] colors = { new Color(66, 209, 127), new Color(247, 198, 105), new Color(102, 201, 238), new Color(246, 173, 125), new Color(30, 203, 196) };

    public static final String X_DIRECTION = "1";// x轴

    public enum IMAGE_FORMAT {
        BMP("bmp"), JPG("jpg"), WBMP("wbmp"), JPEG("jpeg"), PNG("png"), GIF("gif");

        private String value;

        IMAGE_FORMAT(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }

    /************************* 基于三方包解决方案 *****************************/
    /**
     * 剪切图片
     *
     * 待剪切图片路径
     * @param targetPath
     *            裁剪后保存路径（默认为源路径）
     * @param x
     *            起始横坐标
     * @param y
     *            起始纵坐标
     * @param width
     *            剪切宽度
     * @param height
     *            剪切高度
     *
     * @returns 裁剪后保存路径（图片后缀根据图片本身类型生成）
     * @throws IOException
     */
    public static String cutImage(String sourcePath, String targetPath, int x, int y, int width, int height) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image：" + sourcePath);
        }
        if ((null == targetPath) || targetPath.isEmpty()) {
            targetPath = sourcePath;
        }

        String formatName = FilenameUtils.getExtension(file.getName());
        if (null == formatName) {
            return targetPath;
        }
        formatName = formatName.toLowerCase();

        // 防止图片后缀与图片本身类型不一致的情况
        String pathPrefix = getPathWithoutSuffix(targetPath);
        targetPath = pathPrefix + formatName;

        // GIF需要特殊处理
        if (IMAGE_FORMAT.GIF.getValue() == formatName) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }

            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage childImage = decoder.getFrame(i);
                BufferedImage image = childImage.getSubimage(x, y, width, height);
                encoder.addFrame(image);
            }
            encoder.finish();
        } else {
            BufferedImage image = ImageIO.read(file);
            image = image.getSubimage(x, y, width, height);
            ImageIO.write(image, formatName, new File(targetPath));
        }

        return targetPath;
    }

    /**
     * 压缩图片
     *
     * @param sourcePath
     *            待压缩的图片路径
     * @param targetPath
     *            压缩后图片路径（默认为初始路径）
     * @param width
     *            压缩宽度
     * @param height
     *            压缩高度
     *
     * @returns 裁剪后保存路径（图片后缀根据图片本身类型生成）
     * @throws IOException
     */
    public static String zoom(String sourcePath, String targetPath, int width, int height) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image ：" + sourcePath);
        }
        if ((null == targetPath) || targetPath.isEmpty()) {
            targetPath = sourcePath;
        }

        String formatName = FilenameUtils.getExtension(file.getName());
        if (null == formatName) {
            return targetPath;
        }
        String formatNameLowerCase = formatName.toLowerCase();

        // 防止图片后缀与图片本身类型不一致的情况
        String pathPrefix = getPathWithoutSuffix(targetPath);
        targetPath = pathPrefix + formatName;

        // GIF需要特殊处理
        if (IMAGE_FORMAT.GIF.getValue() == formatNameLowerCase) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }

            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage image = zoom(decoder.getFrame(i), width, height);
                encoder.addFrame(image);
            }
            encoder.finish();
        } else {
            BufferedImage image = ImageIO.read(file);
            int w = image.getWidth(null);
            int h = image.getHeight(null);
            if ((w <= width) && (h <= height)) {
                FileUtils.copyFile(file, new File(targetPath));
            } else {
                if (w >= h) {
                    height = (int) Math.round(((h * width * 1.0) / w));
                } else {
                    width = (int) Math.round(((w * height * 1.0) / h));
                }
                BufferedImage zoomImage = zoom(image, width, height);
                ImageIO.write(zoomImage, formatName, new File(targetPath));
            }
        }
        return targetPath;
    }


    /**
     * 压缩图片
     *
     * @param sourcePath
     * @param targetPath
     * @param max
     * @param min
     * @return
     * @throws IOException
     */
    public static String zoomWithMaxAndMin(String sourcePath, String targetPath,int imageWidth,int imageHeight, int max, int min) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image ：" + sourcePath);
        }
        String _targetPath = targetPath;
        if (StringUtils.isBlank(_targetPath)) {
            _targetPath = sourcePath;
        }

        String formatName = FilenameUtils.getExtension(file.getName());
        if (null == formatName) {
            return _targetPath;
        }
        String formatNameLowerCase = formatName.toLowerCase();

        // 防止图片后缀与图片本身类型不一致的情况
        String pathPrefix = getPathWithoutSuffix(_targetPath);
        _targetPath = pathPrefix + formatName;

        // GIF需要特殊处理
        if (IMAGE_FORMAT.GIF.getValue() == formatNameLowerCase) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }
            // 压缩
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(_targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage image = zoomWithMaxAndMin(decoder.getFrame(i), max, max);
                encoder.addFrame(image);
            }
            encoder.finish();
            // 裁剪
        } else {
            catImage(file, _targetPath, imageWidth, imageHeight, max, min);
        }
        return _targetPath;
    }

    /**
     * 压缩图片
     *
     * @param sourcePath
     * @param targetPath
     * @param max
     * @param min
     * @return
     * @throws IOException
     */
    public static String zoomWithMaxAndMin(String sourcePath, String targetPath, int max, int min) throws IOException {
        File file = new File(sourcePath);
        if (!file.exists()) {
            throw new IOException("not found the image ：" + sourcePath);
        }
        String _targetPath = targetPath;
        if (StringUtils.isBlank(_targetPath)) {
            _targetPath = sourcePath;
        }

        String formatName = FilenameUtils.getExtension(file.getName());
        if (null == formatName) {
            return _targetPath;
        }
        String formatNameLowerCase = formatName.toLowerCase();

        // 防止图片后缀与图片本身类型不一致的情况
        String pathPrefix = getPathWithoutSuffix(_targetPath);
        _targetPath = pathPrefix + formatName;

        // GIF需要特殊处理
        if (IMAGE_FORMAT.GIF.getValue() == formatNameLowerCase) {
            GifDecoder decoder = new GifDecoder();
            int status = decoder.read(sourcePath);
            if (status != GifDecoder.STATUS_OK) {
                throw new IOException("read image " + sourcePath + " error!");
            }
            // 压缩
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.start(_targetPath);
            encoder.setRepeat(decoder.getLoopCount());
            for (int i = 0; i < decoder.getFrameCount(); i++) {
                encoder.setDelay(decoder.getDelay(i));
                BufferedImage image = zoomWithMaxAndMin(decoder.getFrame(i), max, max);
                encoder.addFrame(image);
            }
            encoder.finish();
            // 裁剪
        } else {
            BufferedImage image = ImageIO.read(file);
            int imageWidth = image.getWidth(null);
            int imageHeight = image.getHeight(null);
            if ((imageWidth <= max) && (imageHeight <= max)) {
                FileUtils.copyFile(file, new File(_targetPath));
            } else {
                catImage(file, _targetPath, imageWidth, imageHeight, max, min);
            }
        }
        return _targetPath;
    }

    private static void catImage(File file, String targetPath, int imageWidth, int imageHeight, int max, int min) throws IOException {

        if ((imageWidth <= max) && (imageHeight <= max)) { // 如果原图比缩略图还小就不用压缩了
            FileUtils.copyFile(file, new File(targetPath));
            return;
        }
        int w = max;
        int h = max;
        if ((imageWidth >= imageHeight) && (imageWidth > w)) {
            h = (int) Math.round(((imageHeight * w * 1.0) / imageWidth));
        } else if (imageHeight > h) {
            w = (int) Math.round(((imageWidth * h * 1.0) / imageHeight));
        } else {
            w = imageWidth;
            h = imageHeight;
        }
        if (w < min) {
            h = (((min - w) / w) * h) + h;
            w = min;
        }
        if (h < min) {
            w = (((min - h) / h) * w) + w;
            h = min;
        }

        FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath()));
        //ByteArrayInputStream is = new ByteArrayInputStream(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(targetPath);
            Thumbnails.of(fis).size(w, h).toOutputStream(out);
        } catch (IOException e) {
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
            if( fis!=null ){
                fis.close();
            }
        }
    }

    /*********************** 基于JDK 解决方案 ********************************/

    /**
     * 读取图片
     *
     * @param file
     *            图片文件
     * @return 图片数据
     * @throws IOException
     */
    public static BufferedImage[] readerImage(File file) throws IOException {
        BufferedImage sourceImage = ImageIO.read(file);
        BufferedImage[] images = null;
        ImageInputStream iis = ImageIO.createImageInputStream(file);
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (imageReaders.hasNext()) {
            ImageReader reader = imageReaders.next();
            reader.setInput(iis);
            int imageNumber = reader.getNumImages(true);
            images = new BufferedImage[imageNumber];
            for (int i = 0; i < imageNumber; i++) {
                BufferedImage image = reader.read(i);
                if ((sourceImage.getWidth() > image.getWidth()) || (sourceImage.getHeight() > image.getHeight())) {
                    image = zoom(image, sourceImage.getWidth(), sourceImage.getHeight());
                }
                images[i] = image;
            }
            reader.dispose();
            iis.close();
        }
        return images;
    }

    public static BufferedImage loadImage(File file) throws IOException {
        BufferedImage image = ImageIO.read(file);
        return image;
    }
    /**
     * 根据要求处理图片
     *
     * @param images
     *            图片数组
     * @param x
     *            横向起始位置
     * @param y
     *            纵向起始位置
     * @param width
     *            宽度
     * @param height
     *            宽度
     * @return 处理后的图片数组
     * @throws Exception
     */
    public static BufferedImage[] processImage(BufferedImage[] images, int x, int y, int width, int height) throws Exception {
        if (null == images) {
            return images;
        }
        BufferedImage[] oldImages = images;
        images = new BufferedImage[images.length];
        for (int i = 0; i < oldImages.length; i++) {
            BufferedImage image = oldImages[i];
            images[i] = image.getSubimage(x, y, width, height);
        }
        return images;
    }

    public static BufferedImage[] processImage(BufferedImage[] images, int width, int height) throws Exception {
        if (null == images) {
            return images;
        }
        BufferedImage[] oldImages = images;
        images = new BufferedImage[images.length];
        for (int i = 0; i < oldImages.length; i++) {
            BufferedImage image = oldImages[i];
            int x = (image.getWidth() - width) / 2;
            int y = (image.getHeight() - height) / 2;
            images[i] = image.getSubimage(x, y, width, height);
        }
        return images;
    }

    /**
     * 写入处理后的图片到file
     *
     * 图片后缀根据图片格式生成
     *
     * @param images
     *            处理后的图片数据
     * @param formatName
     *            图片格式
     * @param file
     *            写入文件对象
     * @throws Exception
     */
    public static void writerImage(BufferedImage[] images, String formatName, File file) throws Exception {
        Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(formatName);
        if (imageWriters.hasNext()) {
            ImageWriter writer = imageWriters.next();
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index > 0) {
                fileName = fileName.substring(0, index + 1) + formatName;
            }
            String pathPrefix = getFilePrefixPath(file.getPath());
            File outFile = new File(pathPrefix + fileName);
            ImageOutputStream ios = ImageIO.createImageOutputStream(outFile);
            writer.setOutput(ios);

            if (writer.canWriteSequence()) {
                writer.prepareWriteSequence(null);
                for (BufferedImage childImage : images) {
                    IIOImage image = new IIOImage(childImage, null, null);
                    writer.writeToSequence(image, null);
                }
                writer.endWriteSequence();
            } else {
                for (BufferedImage image : images) {
                    writer.write(image);
                }
            }

            writer.dispose();
            ios.close();
        }
    }

    /**
     * 剪切格式图片
     *
     * 基于JDK Image I/O解决方案
     *
     * @param sourceFile
     *            待剪切图片文件对象
     * @param destFile
     *            裁剪后保存文件对象
     * @param x
     *            剪切横向起始位置
     * @param y
     *            剪切纵向起始位置
     * @param width
     *            剪切宽度
     * @param height
     *            剪切宽度
     * @throws Exception
     */
    public static void cutImage(File sourceFile, File destFile, int x, int y, int width, int height) throws Exception {
        // 读取图片信息
        BufferedImage[] images = readerImage(sourceFile);
        // 处理图片
        images = processImage(images, x, y, width, height);
        // 获取文件后缀
        String formatName = FilenameUtils.getExtension(sourceFile.getName());
        destFile = new File(getPathWithoutSuffix(destFile.getPath()) + formatName);

        // 写入处理后的图片到文件
        writerImage(images, formatName, destFile);
    }

    /**
     * 剪切格式图片
     *
     * @param sourceFile
     * @param destFile
     * @param width
     * @param height
     * @throws Exception
     */
    public static void cutImage(File sourceFile, File destFile, int width, int height) throws Exception {
        // 读取图片信息
        BufferedImage[] images = readerImage(sourceFile);
        // 处理图片
        images = processImage(images, width, height);
        // 获取文件后缀
        String formatName = FilenameUtils.getExtension(sourceFile.getName());
        destFile = new File(getPathWithoutSuffix(destFile.getPath()) + formatName);

        // 写入处理后的图片到文件
        writerImage(images, formatName, destFile);
    }

    /**
     * 获取系统支持的图片格式
     */
    public static void getOSSupportsStandardImageFormat() {
        String[] readerFormatName = ImageIO.getReaderFormatNames();
        String[] readerSuffixName = ImageIO.getReaderFileSuffixes();
        String[] readerMIMEType = ImageIO.getReaderMIMETypes();
        System.out.println("========================= OS supports reader ========================");
        System.out.println("OS supports reader format name :  " + Arrays.asList(readerFormatName));
        System.out.println("OS supports reader suffix name :  " + Arrays.asList(readerSuffixName));
        System.out.println("OS supports reader MIME type :  " + Arrays.asList(readerMIMEType));

        String[] writerFormatName = ImageIO.getWriterFormatNames();
        String[] writerSuffixName = ImageIO.getWriterFileSuffixes();
        String[] writerMIMEType = ImageIO.getWriterMIMETypes();

        System.out.println("========================= OS supports writer ========================");
        System.out.println("OS supports writer format name :  " + Arrays.asList(writerFormatName));
        System.out.println("OS supports writer suffix name :  " + Arrays.asList(writerSuffixName));
        System.out.println("OS supports writer MIME type :  " + Arrays.asList(writerMIMEType));
    }

    /**
     * 压缩图片
     *
     * @param src
     *            待压缩图片
     * @param w
     *            压缩图片高度
     * @param h
     *            压缩图片宽度
     */
    private static BufferedImage zoom(BufferedImage src, int w, int h) {
        // 得到合适的压缩大小，按比例。
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if ((width >= height) && (width > w)) {
            h = (int) Math.round(((height * w * 1.0) / width));
        } else if (height > h) {
            w = (int) Math.round(((width * h * 1.0) / height));
        } else {
            w = width;
            h = height;
        }
        int type = src.getType();
        type = type == 0 ? BufferedImage.TYPE_INT_ARGB : type;
        BufferedImage zoom = new BufferedImage(w, h, type);
        Image image = src.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        Graphics graphics = zoom.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.drawImage(image, 0, 0, null);
        return zoom;
    }

    /**
     * 压缩图片
     *
     * @param src
     * @param max
     * @param min
     * @return
     */
    private static BufferedImage zoomWithMaxAndMin(BufferedImage src, int max, int min) {
        // 得到合适的压缩大小，按比例。
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        int w = max;
        int h = max;
        if ((width >= height) && (width > w)) {
            h = (int) Math.round(((height * w * 1.0) / width));
        } else if (height > h) {
            w = (int) Math.round(((width * h * 1.0) / height));
        } else {
            w = width;
            h = height;
        }

        if (w < min) {
            h = (((min - w) / w) * h) + h;
            w = min;
        }
        if (h < min) {
            w = (((min - h) / h) * w) + w;
            h = min;
        }

        int type = src.getType();
        type = type == 0 ? BufferedImage.TYPE_INT_ARGB : type;
        BufferedImage zoom = new BufferedImage(w, h, type);
        Image image = src.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        Graphics graphics = zoom.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.drawImage(image, 0, 0, null);
        return zoom;
    }

    /**
     * 获取某个文件的前缀路径
     *
     * 不包含文件名的路径
     *
     * @param file
     *            当前文件对象
     * @return
     * @throws IOException
     */
    public static String getFilePrefixPath(File file) throws IOException {
        String path = null;
        if (!file.exists()) {
            throw new IOException("not found the file !");
        }
        String fileName = file.getName();
        path = file.getPath().replace(fileName, "");
        return path;
    }

    /**
     * 获取某个文件的前缀路径
     *
     * 不包含文件名的路径
     *
     * @param path
     *            当前文件路径
     * @return 不包含文件名的路径
     * @throws Exception
     */
    public static String getFilePrefixPath(String path) throws Exception {
        if ((null == path) || path.isEmpty()) {
            throw new Exception("文件路径为空！");
        }
        int index = path.lastIndexOf(File.separator);
        if (index > 0) {
            path = path.substring(0, index + 1);
        }
        return path;
    }

    /**
     * 获取不包含后缀的文件路径
     *
     * @param src
     * @return
     */
    public static String getPathWithoutSuffix(String src) {
        String path = src;
        int index = path.lastIndexOf(".");
        if (index > 0) {
            path = path.substring(0, index + 1);
        }
        return path;
    }

    /**
     * 获取文件名
     *
     * @param filePath
     *            文件路径
     * @return 文件名
     * @throws IOException
     */
    public static String getFileName(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("not found the file !");
        }
        return file.getName();
    }

    /**
     * 判断文件是否为缩略图
     *
     * @param file
     * @return
     */
    public static BufferedImage getBufferdImage(File file) {
        try {
            return ImageIO.read(file);
        } catch (Exception e) {
        }
        return null;
    }

    private static List<String> imageExtensions = Arrays.asList(new String[]{"jpg","png","gif","jpeg", "webp"});
    public static boolean isImageSuffix(String extension) {
        imageExtensions.contains(extension);
        for(String ie : imageExtensions){
            if(ie.equals(extension)){
                return true;
            }
        }
        return false;
    }

    /**
     * 等比压缩图像
     *
     * @param src
     *            源图像文件
     * @param target
     *            压缩后要存放的目标文件
     * @param maxWidth
     *            压缩后允许的最大宽度
     * @param maxHeight
     *            压缩后允许的最大高度
     * @throws java.io.IOException
     */
    public static void transform(String src, String target, int maxWidth, int maxHeight) throws Exception {
        String pathPrefix = getPathWithoutSuffix(target);
        File srcFile = new File(src);
        File targetFile = new File(target);
        AffineTransform transform = new AffineTransform();
        BufferedImage biSrc = ImageIO.read(srcFile);
        int width = biSrc.getWidth();
        int height = biSrc.getHeight();
        int newWidth = maxWidth;
        int newHeight = (int) (((double) newWidth / width) * height);
        if (newHeight > maxHeight) {
            newHeight = maxHeight;
            newWidth = (int) (((double) newHeight / height) * width);
        }
        double scaleX = (double) newWidth / width;
        double scaleY = (double) newHeight / height;
        transform.setToScale(scaleX, scaleY);
        AffineTransformOp ato = new AffineTransformOp(transform, null);
        BufferedImage biTarget = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_3BYTE_BGR);
        biTarget.getGraphics().drawImage(biSrc.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
        ato.filter(biSrc, biTarget);
        ImageIO.write(biTarget, pathPrefix, targetFile);
    }

    /**
     * 将图片以Base64方式编码为字符串
     *
     * @param image
     * @return
     * @throws Exception
     */
    public static String encodeImage(File image) throws Exception {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(image);
            byte[] rs = new byte[fis.available()];
            fis.read(rs);
            return new BASE64Encoder().encode(rs);
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 在图片上画线
     *
     * @param sourceFile 源文件
     * @param count 线条数
     */
    public static void drawLineToImage(File sourceFile, String desFile, int count, String direction) {
        if (count <= 0) {
            return;
        }
        try {
            BufferedImage image = ImageIO.read(sourceFile);
            int imageWidth = image.getWidth();// 图片的宽度
            int imageHeight = image.getHeight();// 图片的高度

            Graphics graphics = image.getGraphics();
            graphics.setColor(Color.black);// 线条颜色

            int len = 0;
            // 如果是横向画
            if (X_DIRECTION.equals(direction)) {
                if ((imageWidth % count) == 0) {
                    len = imageWidth / count;
                } else {
                    len = (imageWidth - (imageWidth % count)) / count;
                }
                for (int i = 1; i < count; i++) {
                    graphics.drawLine(len * i, 0, len * i, imageHeight);
                }
            } else {
                if ((imageHeight % count) == 0) {
                    len = imageHeight / count;
                } else {
                    len = (imageHeight - (imageHeight % count)) / count;
                }
                for (int i = 1; i < count; i++) {
                    graphics.drawLine(0, len * i, imageWidth, len * i);
                }
            }
            FileOutputStream fos = new FileOutputStream(desFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            saveAsJPEG(300, image, (float) 0.85, fos);

            bos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 以JPEG编码保存图片
     *
     * @param dpi 分辨率
     * @param image_to_save 要处理的图像图片
     * @param JPEGcompression 压缩比
     * @param fos 文件输出流
     * @throws IOException
     */
    private static void saveAsJPEG(Integer dpi, BufferedImage image_to_save, float JPEGcompression, FileOutputStream fos) throws IOException {
        ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
        ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
        imageWriter.setOutput(ios);
        IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image_to_save), null);
        if ((dpi != null) && !dpi.equals("")) {
            Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
            Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0);
            jfif.setAttribute("Xdensity", Integer.toString(dpi));
            jfif.setAttribute("Ydensity", Integer.toString(dpi));
        }
        if ((JPEGcompression >= 0) && (JPEGcompression <= 1f)) {
            JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
            jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
            jpegParams.setCompressionQuality(JPEGcompression);
        }
        imageWriter.write(imageMetaData, new IIOImage(image_to_save, null, null), null);
        ios.close();
        imageWriter.dispose();
    }


    public static void stringToImage(String content, String savePath, int width, int height) throws Exception {

        File file = new File(savePath);
        Font font = new Font(null, Font.PLAIN, 100);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        g2.setBackground(colors[new Random().nextInt(colors.length)]);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.WHITE);
        g2.setFont(font);

        FontRenderContext context = g2.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;

        g2.drawString(content, (int) x, (int) baseY);

        ImageIO.write(bi, "jpg", file);
    }

    public static void main(String[] args) throws Exception {
        // File file = new File("C:\\Users\\tanyankai\\Desktop\\2.jpg");
        // File target = new File("C:\\Users\\tanyankai\\Desktop\\2_thum.jpg");
        //
        // BufferedImage image = ImageIO.read(new File("C:\\Users\\tanyankai\\Desktop\\142_0.jpg")); // image rotated according to EXIF
        // ByteArrayInputStream is = new ByteArrayInputStream(Files.readAllBytes(Paths.get("C:\\Users\\tanyankai\\Desktop\\142_0.jpg")));
        //
        // Thumbnails.of(is).size(200, 300).outputFormat("jpg").toOutputStream(new FileOutputStream("C:\\Users\\tanyankai\\Desktop\\111_200_300.jpg"));
        // Thumbnails.of(image).size(200, 300).toFile("C:\\Users\\tanyankai\\Desktop\\142_200_300.jpg");

        // Thumbnails.of("C:\\Users\\tanyankai\\Desktop\\1.png").scale(0.25f).toFile("C:\\Users\\tanyankai\\Desktop\\2_25.png");
        // zoomWithMaxAndMin("C:/Users/dufan/Desktop/11.gif", "C:/Users/dufan/Desktop/aa.gif", 200, 88);
        // stringToImage("谭", "/tmp/1.jpg", 80, 80);
        // stringToImage("周", "/tmp/2.jpg", 80, 80);
        // stringToImage("昭", "/tmp/3.jpg", 80, 80);
        // stringToImage("强", "/tmp/4.jpg", 80, 80);
        // stringToImage("陈", "/tmp/5.jpg", 80, 80);
        // 切图
        File sourceFile = new File("C:/Users/dufan/Desktop/tt/tt.jpg");
        // String targetDir = "C:/Users/dufan/Desktop/tt";
        // split(sourceFile, targetDir, 5, "1");
        // 纵向合并
        // List<String> list = new ArrayList<String>();
        // list.add("C:/Users/dufan/Desktop/tt/map_0_0.jpg");
        // list.add("C:/Users/dufan/Desktop/tt/map_1_0.jpg");
        // list.add("C:/Users/dufan/Desktop/tt/map_2_0.jpg");
        // list.add("C:/Users/dufan/Desktop/tt/map_3_0.jpg");
        // list.add("C:/Users/dufan/Desktop/tt/map_4_0.jpg");
        // yPic(list, "C:/Users/dufan/Desktop/tt/纵向合并.jpg");
        // 横向合并
        // List<String> ylist = new ArrayList<String>();
        // ylist.add("C:/Users/dufan/Desktop/tt/y_0_0.jpg");
        // ylist.add("C:/Users/dufan/Desktop/tt/y_0_1.jpg");
        // ylist.add("C:/Users/dufan/Desktop/tt/y_0_2.jpg");
        // ylist.add("C:/Users/dufan/Desktop/tt/y_0_3.jpg");
        // ylist.add("C:/Users/dufan/Desktop/tt/y_0_4.jpg");
        // xPic(ylist, "C:/Users/dufan/Desktop/tt/横向合并.jpg");
        // 画线
//		drawLineToImage(sourceFile, "C:/Users/dufan/Desktop/tt/画线.jpg", 5, "1");
    }
}
